<template>
  <Card
    v-loading="loading"
    :bordered="false"
    :head-style="{ background: '#e7eff6', padding: '0' }"
    :body-style="{ padding: '10px 0' }"
  >
    <template #title>
      <div class="flex gap-2">
        <Button type="primary" @click="handleReturn">
          <template #icon>
            <RollbackOutlined />
          </template>
          返回
        </Button>
        <Button type="primary" @click="handleRefresh">
          <template #icon>
            <RedoOutlined />
          </template>
          刷新
        </Button>
      </div>
    </template>
    <div class="flex gap-2 justify-between pr-3">
      <div class="flex-auto">
        <BasicForm @register="registerForm">
          <template #to="{ model, field }">
            <Input v-model:value="model[field]" @focus="handleFocus(field)" />
          </template>
          <template #csms>
            <div>
              <a-button type="link" @click="handleCS">{{
                iscs ? '删除抄送' : '添加抄送'
              }}</a-button>
            </div>
          </template>
          <template #cc="{ model, field }">
            <Input v-model:value="model[field]" @focus="handleFocus(field)" />
          </template>
          <template #send_now="{ model, field }">
            <FormItemRest>
              <div style="text-align: left">
                <RadioGroup v-model:value="model[field]">
                  <Radio :style="radioStyle" value="yes">立即发送</Radio>
                  <Radio :style="radioStyle" value="no">
                    定时发送
                    <DatePicker
                      class="ml-2"
                      v-model:value="dataRef.send_time"
                      value-format="YYYY-MM-DD HH:mm"
                      format="YYYY-MM-DD HH:mm"
                      :show-time="true"
                    />
                  </Radio>
                </RadioGroup>
              </div>
            </FormItemRest>
          </template>
          <template #att>
            <FormItemRest>
              <div class="text-left">
                <Upload
                  :file-list="fileList"
                  :before-upload="beforeUpload"
                  @remove="handleRemove"
                  multiple
                >
                  <a-button>
                    <upload-outlined />
                    上传文件
                  </a-button>
                </Upload>
              </div>
              <div class="mt-5" v-if="dataRef.attachments && dataRef.attachments.length">
                <div v-for="(item, index) in dataRef.attachments" :key="index">
                  <a @click="handleDonwload(item)">{{ item.name }}</a>
                  <a @click="handlePreview(item)" title="预览" v-if="item.previewUrl" class="ml-3"
                    ><EyeOutlined style="color: rgba(28, 106, 235, 1)"
                  /></a>
                  <CloseOutlined class="ml-3" @click="handleClickDeleteFile(index)" />
                </div>
              </div>
            </FormItemRest>
          </template>
        </BasicForm>
        <div class="flex justify-center gap-2">
          <template v-if="type == 'reply'">
            <a-button type="primary" @click="handleSend('reply')">发送</a-button>
            <a-button @click="handleSend('draft')">保存草稿</a-button>
            <a-button @click="handleShowMore">高级功能</a-button>
          </template>
          <template v-else>
            <a-button type="primary" @click="handleSend('send')">发送</a-button>
            <a-button @click="handleSend('draft')">保存草稿</a-button>
            <a-button @click="handleShowMore">高级功能</a-button>
          </template>
        </div>
      </div>
      <div class="w-200px">
        <Card title="常用联系人" :bodyStyle="{ padding: '5px', height: '65vh' }">
          <Scrollbar>
            <div
              v-for="(item, index) in recentlyEmailList"
              :key="index"
              class="leading-relaxed cursor-pointer"
              style="
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                padding: 0 10px;
              "
              @click="handleClickUser(item)"
            >
              <Tooltip :title="item.emailAddr"> {{ item.emailAddr }} </Tooltip>
              <Popconfirm
                placement="leftBottom"
                @confirm="handleClickDeleteRecentlyEmail(item.id)"
                title="确定删除吗？"
              >
                <CloseOutlined class="ml-3" style="color: red" />
              </Popconfirm>
            </div>
          </Scrollbar>
        </Card>
      </div>
    </div>
  </Card>
</template>
<script lang="ts" setup>
  import { ref, nextTick, onMounted, inject, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, radioStyle } from './writeboxForm.data';
  import {
    Form,
    Radio,
    RadioGroup,
    DatePicker,
    Card,
    Upload,
    UploadProps,
    Button,
    Tooltip,
    Input,
    Popconfirm,
  } from 'ant-design-vue';
  import {
    UploadOutlined,
    RedoOutlined,
    RollbackOutlined,
    CloseOutlined,
  } from '@ant-design/icons-vue';
  import {
    getEmailSend,
    getEmailUpdateDraft,
    getEmailReply,
    getEmailShowMail,
    getEmailListRecentlyEmail,
    getEmailDelRecentlyEmail,
  } from '/@/api/email/externalEmail';
  import { useRouter } from 'vue-router';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Scrollbar } from '/@/components/Scrollbar';
  import { dateUtil as dayjs } from '/@/utils/dateUtil';
  import { useUserStore } from '/@/store/modules/user';
  import { isEmpty } from '/@/utils/is';
  import { downloadByUrl } from '/@/utils/file/download';
  const props = defineProps({
    currentRecord: {
      type: Object,
      default: () => {
        return {};
      },
    },
    type: {
      type: String,
      default: '',
    },
  });
  const emit = defineEmits(['handle-return', 'handle-sand', 'handle-draft']);
  const internalEmail = inject('internalEmail') as any;
  const { currentRoute } = useRouter();
  const { createMessage } = useMessage();
  const FormItemRest = Form.ItemRest;
  const iscs = ref(false);
  const ishj = ref(false);
  const loading = ref(false);
  const dataRef = ref<Recordable>({
    send_now: 'yes',
    send_time: '',
    // sendDate: '',
    to: '',
    cc: '',
    bcc: '',
    // isToOutBox: 'true',
    isSaveToSendBox: true,
    receipt_state: 0,
    msg_level: 0,
    id: -1,
    email: '',
    // timeSend:0 ,//前端处理，打钩后选择时间，不打钩就置空 send_time
  });

  const [registerForm, { resetFields, validate, setFieldsValue, updateSchema }] = useForm({
    labelWidth: 80,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo;
  const oldDataRef = ref<Recordable>({});
  const init = () => {
    nextTick(async () => {
      console.log('internalEmail', internalEmail);
      iscs.value = false;
      getEmailListRecentlyEmailData();
      setFields();
      resetFields();

      // dataRef.value.email = internalEmail.emailInfo.value.id;
      dataRef.value.username = userInfo.name;
      // dataRef.value.cancelTime = 1;
      dataRef.value.email = internalEmail.emailInfo.value.email;
      const { currentRecord, type } = props;
      console.log('currentRecord', currentRecord);
      if (!isEmpty(currentRecord)) {
        const res = await getEmailShowMail({
          emailId: internalEmail.emailInfo.value.id,
          id: currentRecord.id,
        });
        oldDataRef.value = res || {};
        oldDataRef.value.receipt_state = oldDataRef.value.receiptState;
        oldDataRef.value.msg_level = oldDataRef.value.msgLevel;
        if (oldDataRef.value.copyReceiver) {
          oldDataRef.value.cc = oldDataRef.value.copyReceiver;
          handleCS();
        }
        if (oldDataRef.value.sendTime) {
          oldDataRef.value.send_now = 'no';
          oldDataRef.value.send_time = dayjs(oldDataRef.value.sendTime).format('YYYY-MM-DD HH:mm');
        }
        if (type == 'reply') {
          dataRef.value.subject = `回复：${unref(oldDataRef).subject}`;
          dataRef.value.to = unref(oldDataRef).sender;
          dataRef.value.content =
            `<br><br><br><br><br><br><br><p>------------------原始邮件------------------</p>` +
            unref(oldDataRef).content;
          dataRef.value.attachments = unref(oldDataRef).attachments;
        } else if (type == 'draftbox' || type == 'outBox') {
          dataRef.value = {
            ...dataRef.value,
            ...oldDataRef.value,
            to: oldDataRef.value.receiver,
          };
        } else if (type == 'transmit') {
          dataRef.value = {
            ...dataRef.value,
            ...oldDataRef.value,
            to: '',
          };
          dataRef.value.subject = `Fw：${unref(dataRef).subject}`;
          dataRef.value.content =
            `<br><br><br><br><br><br><br><p>------------------转发邮件信息------------------</p>` +
            unref(dataRef).content;
        }
      }

      setFieldsValue({ ...dataRef.value });
    });
  };

  const recentlyEmailList = ref([]);
  //最近联系人
  const getEmailListRecentlyEmailData = async () => {
    const res = await getEmailListRecentlyEmail({ emailId: internalEmail.emailInfo.value.id });
    recentlyEmailList.value = res || [];
  };
  //删除最近联系人
  const handleClickDeleteRecentlyEmail = async (id) => {
    try {
      const params = {
        emailId: internalEmail.emailInfo.value.id,
        id: id,
      };
      const res = await getEmailDelRecentlyEmail(params);
      createMessage.success('操作成功');
      await getEmailListRecentlyEmailData();
    } catch (error) {}
  };

  onMounted(init);

  //聚焦的字段
  const focusField = ref('');
  //聚焦选择框
  const handleFocus = (field) => {
    focusField.value = field;
    console.log('handleFocus', field);
  };

  //选择常用人
  const handleClickUser = (item) => {
    if (unref(focusField)) {
      setFieldsValue({ [unref(focusField)]: item.emailAddr });
    }
  };

  const fileList = ref<UploadProps['fileList']>([]);
  const handleRemove: UploadProps['onRemove'] = (file) => {
    const index = fileList.value.indexOf(file);
    const newFileList = fileList.value.slice();
    newFileList.splice(index, 1);
    fileList.value = newFileList;
  };
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    fileList.value = [...fileList.value, file];
    return false;
  };

  const handleReturn = () => {
    emit('handle-return');
  };
  const handleRefresh = () => {
    init();
  };
  const handleCS = () => {
    iscs.value = !iscs.value;
    if (iscs.value) {
      updateSchema([
        {
          field: 'cc',
          ifShow: true,
        },
      ]);
    } else {
      updateSchema([
        {
          field: 'cc',
          ifShow: false,
        },
      ]);
    }
  };

  const handleSuccess = () => {
    fileList.value = [];
    resetFields();
  };
  const handleSend = async (type) => {
    try {
      console.log('fileList', fileList.value);
      const values = await validate();
      console.log('values', values);
      console.log('fileList', fileList.value);
      const data = Object.assign({}, dataRef.value, values);
      if (data.send_now == 'no' && !data.send_time) {
        createMessage.warning('定时发送，时间不能为空');
        return;
      }
      data.emailId = internalEmail.emailInfo.value.id;
      const url = `?emailId=${internalEmail.emailInfo.value.id}&send_now=${data.send_now}`;
      if (props.type == 'transmit') {
        if (data.attachments && data.attachments.length) {
          data.attIdsRemoved = data.attachments.map((item) => item.id);
        }
      }
      Reflect.deleteProperty(data, 'att');
      Reflect.deleteProperty(data, 'attachments');
      Reflect.deleteProperty(data, 'csms');

      // data.sendDate = dayjs().format('YYYY-MM-DD');
      console.log('data', data);
      fileList.value?.forEach((item, index) => {
        data[`att${index + 1}`] = item;
      });
      const formata = new FormData();
      for (let v in data) {
        formata.append(v, data[v]);
      }
      loading.value = true;
      if (type == 'send') {
        await getEmailSend(formata, url);
        internalEmail.handleSend();
        // emit('handle-sand');
        // if (props.type == 'reply') {
        // } else if (props.type == 'draftbox' || type == 'outBox') {
        //   handleReturn();
        // } else if (props.type == 'transmit') {
        //   handleReturn();
        // }
      } else if (type == 'draft') {
        await getEmailUpdateDraft(formata, url);
        // emit('handle-draft');
        internalEmail.handleDraft();
      } else if (type == 'reply') {
        await getEmailReply(formata, url);
        handleReturn();
      }

      createMessage.success('操作成功');
      handleSuccess();
    } catch (error) {
      console.log('handleSend', error);
    } finally {
      loading.value = false;
    }
  };
  const handleShowMore = () => {
    ishj.value = !ishj.value;
    setFields();
  };
  const setFields = () => {
    if (ishj.value) {
      updateSchema([
        {
          field: 'send_now',
          ifShow: true,
        },
      ]);
      updateSchema([
        {
          field: 'receipt_state',
          ifShow: true,
        },
      ]);
      updateSchema([
        {
          field: 'msg_level',
          ifShow: true,
        },
      ]);
    } else {
      updateSchema([
        {
          field: 'send_now',
          ifShow: false,
        },
      ]);
      updateSchema([
        {
          field: 'receipt_state',
          ifShow: false,
        },
      ]);
      updateSchema([
        {
          field: 'msg_level',
          ifShow: false,
        },
      ]);
    }
  };
  const serverInfo = userStore.getServerInfo;
  //下载
  const handleDonwload = (record) => {
    const path = record.visualPath + '/' + record.diskName;
    const fileName = record.name;
    const url = path
      ? serverInfo.rootPath + (path && path.startsWith('/') ? path : `/${path}`)
      : '';
    downloadByUrl({ url, fileName });
  };

  const handlePreview = computed(() => (record: any) => {
    const rootPath = serverInfo.rootPath;
    window.open(rootPath + '/' + record.previewUrl);
  });
  //删除附件
  const handleClickDeleteFile = (index) => {
    dataRef.value.attachments.splice(index, 1);
  };
</script>

<style lang="less" scoped>
  :deep(.ant-card-head-title) {
    padding: 8px 8px 0;
  }
</style>
